const Router = require('@koa/router');
const { Order, OrderTicket, Ticket, sequelize, Op } = require('../databases/index');
const authMiddleware = require('../middlewares/auth');

const router = new Router({
    prefix: '/order'
});

// 创建订单
router.post('/create', authMiddleware, async (ctx) => {
    const { userId } = ctx.state.user;
    console.log('userId', userId);
    const { tickets, paymentMethod } = ctx.request.body;

    // 验证请求数据
    if (!tickets || !Array.isArray(tickets) || tickets.length === 0) {
        ctx.status = 400;
        ctx.body = {
            code: 400,
            message: '请提供有效的门票信息'
        };
        return;
    }

    try {
        // 开始事务
        const transaction = await sequelize.transaction();
        
        try {
            // 计算订单总价
            let totalPrice = 0;
            const ticketDetails = [];
            
            // 获取门票信息并计算总价
            for (const item of tickets) {
                const ticket = await Ticket.findByPk(item.ticketId, {
                    transaction
                });
                
                if (!ticket) {
                    throw new Error(`门票ID ${item.ticketId} 不存在`);
                }
                
                const quantity = item.quantity || 1;
                const subtotal = ticket.price * quantity;
                totalPrice += subtotal;
                
                ticketDetails.push({
                    ticketId: ticket.ticketId,
                    quantity,
                    unitPrice: ticket.price
                });
            }
            
            // 创建订单
            const order = await Order.create({
                userId,
                totalPrice,
                status: 'pending',
                paymentMethod
            }, {
                transaction
            });
            
            // 创建订单-门票关联记录
            const orderTicketPromises = ticketDetails.map(detail => 
                OrderTicket.create({
                    orderId: order.orderId,
                    ...detail
                }, {
                    transaction
                })
            );
            
            await Promise.all(orderTicketPromises);
            
            // 提交事务
            await transaction.commit();
            
            ctx.body = {
                code: 200,
                message: '订单创建成功',
                data: order
            };
        } catch (error) {
            // 回滚事务
            await transaction.rollback();
            throw error;
        }
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `创建订单失败: ${error.message}`
        };
    }
});

// 获取订单列表（支持用户筛选、分页）
// 权限控制：
// - 管理员可以查询所有订单或通过filterUserId参数筛选特定用户的订单
// - 非管理员只能查询自己的订单
router.get('/user', authMiddleware, async (ctx) => {
    const { userId: currentUserId, role } = ctx.state.user;
    const { page = 1, pageSize = 10, startDate, endDate, filterUserId, status } = ctx.query;
    
    try {
        // 构建查询条件
        const whereCondition = {};
        
        // 添加状态筛选（如果有）
        if (status) {
            whereCondition.status = status;
        }
        
        // 权限控制：
        // 1. 管理员可以查询所有订单或指定用户的订单
        // 2. 非管理员只能查询自己的订单
        if (role === 'admin') {
            // 如果提供了filterUserId，则按指定用户筛选
            if (filterUserId) {
                whereCondition.userId = filterUserId;
            }
        } else {
            // 非管理员只能查看自己的订单
            whereCondition.userId = currentUserId;
        }
        
        // 添加日期范围查询（如果有）
        if (startDate && endDate) {
            whereCondition.createdAt = {
                [Op.between]: [new Date(startDate), new Date(endDate + ' 23:59:59')]
            };
        }
        
        // 查询总数
        const total = await Order.count({ where: whereCondition });
        
        // 查询分页数据
        const orders = await Order.findAll({
            where: whereCondition,
            include: [
                {
                    model: OrderTicket,
                    as: 'orderTickets',
                    include: [
                        {
                            model: Ticket,
                            as: 'ticket'
                        }
                    ]
                }
            ],
            order: [['createdAt', 'DESC']],
            offset: (page - 1) * pageSize,
            limit: parseInt(pageSize)
        });
        
        ctx.body = {
            code: 200,
            message: '获取订单列表成功',
            data: {
                list: orders,
                total,
                page: parseInt(page),
                pageSize: parseInt(pageSize)
            }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `获取订单列表失败: ${error.message}`
        };
    }
});

// 订单统计（所有订单）
router.get('/stats', authMiddleware, async (ctx) => {
    try {
        console.log('订单统计请求 - 后台管理系统');
        
        // 获取各种状态的订单数量（统计所有订单，不区分用户）
        const pendingCount = await Order.count({ where: { status: 'pending' } });
        const paidCount = await Order.count({ where: { status: 'paid' } });
        const canceledCount = await Order.count({ where: { status: 'canceled' } });
        const completedCount = await Order.count({ where: { status: 'completed' } });
        const totalCount = await Order.count({});
        
        // 获取总消费金额（仅统计已支付的订单）
        const totalAmountResult = await Order.sum('totalPrice', { where: { status: 'paid' } });
        const totalAmount = totalAmountResult || 0;
        
        console.log('订单统计结果 - 所有订单:', {
            pending: pendingCount,
            paid: paidCount,
            canceled: canceledCount,
            completed: completedCount,
            total: totalCount,
            totalAmount: totalAmount
        });
        
        ctx.body = {
            code: 200,
            message: '获取所有订单统计成功',
            data: {
                pending: pendingCount,
                paid: paidCount,
                canceled: canceledCount,
                completed: completedCount,
                total: totalCount,
                totalAmount: totalAmount
            }
        };
    } catch (error) {
        console.error('订单统计错误:', error);
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `获取订单统计失败: ${error.message}`
        };
    }
});

// 获取单个订单详情
router.get('/:orderId', authMiddleware, async (ctx) => {
    const { userId } = ctx.state.user;
    const { orderId } = ctx.params;
    
    try {
        const order = await Order.findByPk(orderId, {
            include: [
                {
                    model: OrderTicket,
                    as: 'orderTickets',
                    include: [
                        {
                            model: Ticket,
                            as: 'ticket'
                        }
                    ]
                }
            ]
        });
        
        if (!order) {
            ctx.status = 404;
            ctx.body = {
                code: 404,
                message: '订单不存在'
            };
            return;
        }
        
        // 权限验证：管理员可以查看所有订单，非管理员只能查看自己的订单
        if (ctx.state.user.role !== 'admin' && order.userId !== userId) {
            ctx.status = 403;
            ctx.body = {
                code: 403,
                message: '无权访问该订单'
            };
            return;
        }
        
        ctx.body = {
            code: 200,
            message: '获取订单详情成功',
            data: order
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `获取订单详情失败: ${error.message}`
        };
    }
});

// 更新订单状态（支付或取消）
router.put('/update/:orderId', authMiddleware, async (ctx) => {
    const { userId } = ctx.state.user;
    const { orderId } = ctx.params;
    const { status, paymentMethod } = ctx.request.body;
    
    try {
        const order = await Order.findByPk(orderId);
        
        if (!order) {
            ctx.status = 404;
            ctx.body = {
                code: 404,
                message: '订单不存在'
            };
            return;
        }
        
        // 权限验证：管理员可以更新所有订单，非管理员只能更新自己的订单
        if (ctx.state.user.role !== 'admin' && order.userId !== userId) {
            ctx.status = 403;
            ctx.body = {
                code: 403,
                message: '无权更新该订单'
            };
            return;
        }
        
        // 准备更新数据
        const updateData = {};
        if (status) {
            updateData.status = status;
            
            // 如果状态变为已支付，记录支付时间
            if (status === 'paid') {
                updateData.paymentTime = new Date();
            }
        }
        
        if (paymentMethod) {
            updateData.paymentMethod = paymentMethod;
        }
        
        await order.update(updateData);
        
        ctx.body = {
            code: 200,
            message: '订单更新成功',
            data: order
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `更新订单失败: ${error.message}`
        };
    }
});

// 删除订单（通常只允许删除未支付的订单）
router.delete('/delete/:orderId', authMiddleware, async (ctx) => {
    const { userId } = ctx.state.user;
    const { orderId } = ctx.params;
    
    try {
        // 开始事务
        const transaction = await sequelize.transaction();
        
        try {
            const order = await Order.findByPk(orderId, {
                transaction
            });
            
            if (!order) {
                throw new Error('订单不存在');
            }
            
            // 权限验证：管理员可以删除所有订单，非管理员只能删除自己的订单
            if (ctx.state.user.role !== 'admin' && order.userId !== userId) {
                throw new Error('无权删除该订单');
            }
            
            // 通常只允许删除未支付的订单
            if (order.status !== 'pending') {
                throw new Error('已支付或已完成的订单不能删除');
            }
            
            // 先删除订单-门票关联记录
            await OrderTicket.destroy({
                where: { orderId },
                transaction
            });
            
            // 再删除订单
            await order.destroy({
                transaction
            });
            
            // 提交事务
            await transaction.commit();
            
            ctx.body = {
                code: 200,
                message: '订单删除成功'
            };
        } catch (error) {
            // 回滚事务
            await transaction.rollback();
            throw error;
        }
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `删除订单失败: ${error.message}`
        };
    }
});

//状态查询（支持分页）
router.get('/status/:status', authMiddleware, async (ctx) => {
    const { userId } = ctx.state.user;
    const { status } = ctx.params;
    const { page = 1, pageSize = 10, startDate, endDate } = ctx.query;
    
    try {
        // 构建查询条件
        const whereCondition = { userId, status };
        
        // 添加日期范围查询（如果有）
        if (startDate && endDate) {
            whereCondition.createdAt = {
                [Op.between]: [new Date(startDate), new Date(endDate + ' 23:59:59')]
            };
        }
        
        // 查询总数
        const total = await Order.count({ where: whereCondition });
        
        // 查询分页数据
        const orders = await Order.findAll({
            where: whereCondition,
            include: [
                {
                    model: OrderTicket,
                    as: 'orderTickets',
                    include: [
                        {
                            model: Ticket,
                            as: 'ticket'
                        }
                    ]
                }
            ],
            order: [['createdAt', 'DESC']],
            offset: (page - 1) * pageSize,
            limit: parseInt(pageSize)
        });
        
        ctx.body = {
            code: 200,
            message: '获取订单列表成功',
            data: {
                list: orders,
                total,
                page: parseInt(page),
                pageSize: parseInt(pageSize)
            }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `获取订单列表失败: ${error.message}`
        };
    }
});

// 完成订单
router.put('/complete/:orderId', authMiddleware, async (ctx) => {
    const { userId } = ctx.state.user;
    const { orderId } = ctx.params;
    
    try {
        const order = await Order.findByPk(orderId);
        
        if (!order) {
            ctx.status = 404;
            ctx.body = {
                code: 404,
                message: '订单不存在'
            };
            return;
        }
        
        // 确保用户只能更新自己的订单
        if (order.userId !== userId) {
            ctx.status = 403;
            ctx.body = {
                code: 403,
                message: '无权更新该订单'
            };
            return;
        }
        
        // 只有已支付的订单才能标记为已完成
        if (order.status !== 'paid') {
            ctx.status = 400;
            ctx.body = {
                code: 400,
                message: '只有已支付的订单才能标记为已完成'
            };
            return;
        }
        
        await order.update({
            status: 'completed',
            completedAt: new Date()
        });
        
        ctx.body = {
            code: 200,
            message: '订单已标记为已完成',
            data: order
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `更新订单失败: ${error.message}`
        };
    }
});


//查询所有订单
router.get('/all/order', authMiddleware, async (ctx) => {
    try {
        const orders = await Order.findAll({
            include: [
                {
                    model: OrderTicket,
                    as: 'orderTickets',
                    include: [
                        {
                            model: Ticket,
                            as: 'ticket'
                        }
                    ]
                }
            ],
            order: [['createdAt', 'DESC']]
        });
        ctx.body = {
            code: 200,
            message: '获取所有订单成功',
            data: orders
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `获取所有订单失败: ${error.message}`
        };
    }
});


//获取最新的5个订单
router.get('/latest/order', authMiddleware, async (ctx) => {
    try {
        const orders = await Order.findAll({
            include: [
                {
                    model: OrderTicket,
                    as: 'orderTickets',
                    include: [
                        {
                            model: Ticket,
                            as: 'ticket'
                        }
                    ]
                }
            ],
            order: [['createdAt', 'DESC']],
            limit: 5
        });
        ctx.body = {
            code: 200,
            message: '获取最新订单成功',
            data: orders
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `获取最新订单失败: ${error.message}`
        };
    }
});

//获取月订单统计
router.get('/monthly/stats', authMiddleware, async (ctx) => {
    try {
        const currentDate = new Date();
        const currentMonth = currentDate.getMonth();
        const currentYear = currentDate.getFullYear();
        
        // 计算本月的开始和结束日期
        const startOfMonth = new Date(currentYear, currentMonth, 1);
        const endOfMonth = new Date(currentYear, currentMonth + 1, 0);
        
        // 查询本月所有订单
        const orders = await Order.findAll({
            where: {
                createdAt: {
                    [Op.between]: [startOfMonth, endOfMonth]
                }
            },
            include: [
                {
                    model: OrderTicket,
                    as: 'orderTickets',
                    include: [
                        {
                            model: Ticket,
                            as: 'ticket'
                        }
                    ]
                }
            ],
            order: [['createdAt', 'DESC']]
        });
        
        // 计算统计数据
        const totalOrders = orders.length;
        const totalSales = orders.reduce((sum, order) => sum + (order.totalPrice || 0), 0);
        const completedOrders = orders.filter(order => order.status === 'completed').length;
        const pendingOrders = orders.filter(order => order.status === 'pending').length;
        const paidOrders = orders.filter(order => order.status === 'paid').length;
        const canceledOrders = orders.filter(order => order.status === 'canceled').length;
        
        // 按日期分组统计
        const dailyStats = [];
        const dateMap = new Map();
        
        orders.forEach(order => {
            const date = new Date(order.createdAt).toISOString().split('T')[0];
            if (!dateMap.has(date)) {
                dateMap.set(date, {
                    date,
                    orders: 0,
                    sales: 0
                });
            }
            
            const stats = dateMap.get(date);
            stats.orders += 1;
            stats.sales += order.totalPrice || 0;
        });
        
        // 转换为数组并按日期排序
        dateMap.forEach(value => {
            dailyStats.push(value);
        });
        dailyStats.sort((a, b) => new Date(a.date) - new Date(b.date));
        
        ctx.body = {
            code: 200,
            message: '获取月订单统计成功',
            data: {
                totalOrders,
                totalSales: Number(totalSales.toFixed(2)),
                completedOrders,
                pendingOrders,
                paidOrders,
                canceledOrders,
                dailyStats,
                orders // 保留原始订单数据供前端使用
            }
        };
    } catch (error) {
        console.error('获取月订单统计失败:', error);
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: `获取月订单统计失败: ${error.message}`
        };
    }
});

module.exports = router;